﻿
CREATE PROCEDURE [dbo].[MngRecalcCounter] (
	@CounterName varchar(20)
)
AS
-- Черноусов ОП 25.07.2006 расчитывает новое значение идентификатора для справочников и других таблиц
DECLARE @intMaxId int

IF @CounterName = 'Common'
BEGIN 
	SELECT @intMaxId = max(MaxId+1) FROM (
	SELECT max(Id) AS MaxId from CA.Assortment
	UNION ALL
	SELECT max(Id) from CA.Contragents
	UNION ALL
	SELECT max(Id) from CA.Goods
	UNION ALL
	SELECT max(Id) from CO.Catalog
	UNION ALL
	SELECT max(Id) from CO.Manufacturers
	UNION ALL
	SELECT max(Id) from CA.GoodsVsContragents
	UNION ALL
	SELECT max(Id) from CD.ManageDocLines
	UNION ALL
	SELECT max(Id) from [CD].[CashRegisterShifts]
	UNION ALL
	SELECT max(Id) from [CD].[CashRegisters]
	) T

	IF @intMaxId Is Null SET @intMaxId = 1
	ELSE BEGIN
		IF @intMaxId > 100000000 SET @intMaxId = @intMaxId % 100000000 ---([Id]/(100000000))
	END

	DBCC CHECKIDENT ('PR.CounterCommon', RESEED, @intMaxId) -- новое значение IDENTITY
END

IF @CounterName = 'Documents'
BEGIN 
	SELECT @intMaxId = max(MaxId+1) FROM (
	SELECT max(Id) AS MaxId from CA.Documents
	) T

	IF @intMaxId Is Null SET @intMaxId = 1
	ELSE BEGIN
		IF @intMaxId > 100000000 SET @intMaxId = @intMaxId % 100000000 ---([Id]/(100000000))
	END

	DBCC CHECKIDENT ('PR.CounterDocuments', RESEED, @intMaxId) -- новое значение IDENTITY
END

IF @CounterName = 'GoodsLines'
BEGIN 
	SELECT @intMaxId = max(MaxId+1) FROM (
	SELECT max(Id) AS MaxId from CD.InputLines
	UNION ALL
	SELECT max(Id) from CD.Parties
	UNION ALL
	SELECT max(Id) from CA.GoodsDocLines
	UNION ALL
	SELECT max(Id) from CD.RepriceWriteoffLines
	UNION ALL
	SELECT max(Id) from CD.InventoryLines
	) T

	IF @intMaxId Is Null SET @intMaxId = 1
	ELSE BEGIN
		IF @intMaxId > 100000000 SET @intMaxId = @intMaxId % 100000000 ---([Id]/(100000000))
	END

	DBCC CHECKIDENT ('PR.CounterGoodsLines', RESEED, @intMaxId) -- новое значение IDENTITY
END


	SELECT @intMaxId 

RETURN 0